package com.woniuxy.oldmanapi.utils;

import com.woniuxy.oldmanapi.vo.AccountVo;
import com.woniuxy.oldmanapi.vo.JwtInfo;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class JwtUtils {
    @Autowired
    JwtInfo jwtInfo ;

    /**
     * 生成Token
     * @return
     */
    public String createToken(AccountVo accountVo){
        try {
            //构建出一个Jwt的构建者对象
            JwtBuilder jwtBuilder = Jwts.builder();
            //设置头信息
            jwtBuilder.setHeaderParam("alg",jwtInfo.getAlg());
            jwtBuilder.setHeaderParam("typ",jwtInfo.getTyp());

            //设置载荷信息
            jwtBuilder.setIssuer(jwtInfo.getIssuer());
            jwtBuilder.setSubject(jwtInfo.getSubject());
            //设置过期时间  30分钟
            jwtBuilder.setExpiration(new Date(new Date().getTime()+jwtInfo.getExpiration()));

            //设置自定义信息
            jwtBuilder.claim(jwtInfo.getUserName(),accountVo.getUsername());
            jwtBuilder.claim(jwtInfo.getUserId()+"",accountVo.getUsername());
            //不建议设置密码

            //设置 签证信息
            //final String SECRET = properties.getProperty("secret");
            //做签证
            jwtBuilder.signWith(SignatureAlgorithm.HS256,jwtInfo.getSecret());
            String compact = jwtBuilder.compact();

            return compact ;
        }catch (RuntimeException e){
            e.printStackTrace();
            throw new RuntimeException("JWT的token生成失败",e);
        }
    }

    /**
     * 解析JWT的token
     * @param token
     * @return
     */
    public Claims parseToken(String token){
        try {
            JwtParser jwtParser = Jwts.parser();
            Jws<Claims> claimsJws = jwtParser.setSigningKey(jwtInfo.getSecret()).parseClaimsJws(token);
            Claims body = claimsJws.getBody();

            return body;
        }catch (ExpiredJwtException e){
            e.printStackTrace();
            throw  new ExpiredJwtException(null,null,"token已经过期！",e);
        }catch (SignatureException e1){
            e1.printStackTrace();
            throw new SignatureException("密钥不正确！",e1);
        }catch (RuntimeException e2){
            e2.printStackTrace();
            throw new RuntimeException("解析token出错！",e2);
        }
    }
    /**
     * 获取 token中的用户名
     * @return
     */
    public String getUsername(String token){
        Claims claims = this.parseToken(token);
        return (String) claims.get(jwtInfo.getUserName());
    }
    public int getId(String token){
        Claims claims = this.parseToken(token);
        return (int) claims.get(jwtInfo.getUserId());
    }
}
